package com.atguigu.spring.controller;

import com.atguigu.spring.entity.Student;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.net.InetSocketAddress;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

// @ResponseBody
// @Controller
@RestController
public class Demo03ControllerReceiveData {

    // @ResponseBody
    @RequestMapping("/param/one/name/one/value")
    public String oneNameOneValue(
            // 为了接收请求参数，给方法形参标记 @RequestParam 注解
            // 在 @RequestParam 注解中指定请求参数的名称
            // required 属性设置为 false：表示请求参数非必须
            @RequestParam(value = "subject", required = false, defaultValue = "PHP") String subject,

            // HTTP 协议传输数据都是字符串类型，但是业务中又往往需要其它类型
            // SpringMVC 提供了自动的类型转换
            // 当请求参数名和形参名一致，注解部分可以省略
            /*@RequestParam("score")*/ Double score) {
        return "ok subject = " + subject + " score = " + score;
    }

    // @ResponseBody
    @RequestMapping("/param/one/name/multi/value")
    public String oneNameMultiValue(
            @RequestParam("team") List<String> teamList
    ) {

        for (String team : teamList) {
            System.out.println("team = " + team);
        }

        return "ok";
    }

    // @ResponseBody
    @RequestMapping("/param/entity")
    public String saveStudent(
            // 使用实体类接收请求参数时，不加任何注解
            Student student) {
        return "ok " + student;
    }

    // @ResponseBody
    @RequestMapping("/json/request/body/save/student")
    public String saveStudentJSON(
            // 前端以请求体 JSON 格式发送数据，我们在 Controller 方法中
            // 需要使用实体类接收，并且在实体类前标记 @RequestBody 注解
            @RequestBody Student student) {
        return "ok " + student;
    }

    // 前端发送实际的请求路径举例：
    // /test/path/variable/111/harry
    // /test/path/variable/222/jerry
    // /test/path/variable/333/peter
    // @ResponseBody
    @RequestMapping("/test/path/variable/{age}/{name}")
    public String testPathVariable(@PathVariable Integer age, @PathVariable String name) {
        return "ok age = " + age + " name = " + name;
    }

    // @ResponseBody
    @RequestMapping("/receive/http/entity")
    public Map<String, Object> test05(HttpEntity<String> httpEntity) {

        String requestBody = httpEntity.getBody();
        HttpHeaders headers = httpEntity.getHeaders();
        List<MediaType> acceptList = headers.getAccept();
        InetSocketAddress host = headers.getHost();
        MediaType contentType = headers.getContentType();

        Map<String, Object> responseMap = new HashMap<>();
        responseMap.put("requestBody", requestBody);
        responseMap.put("acceptList", acceptList);
        responseMap.put("host", host.getHostName());
        responseMap.put("contentType", contentType);

        return responseMap;
    }
}
